<template>
  <div class="register">
    <Header-Comp title="注册" :leftIconCallback="goBack" />

    <div class="register-center">
      <van-form ref="form" validate-first>
        <van-cell-group>
          <van-field
            v-model.trim="form.mobile"
            clearable
            type="number"
            placeholder="请输入手机号"
            :rules="phoneRules"
            @input="getAccountNo"
          >
            <van-icon
              class="iconfont icon-shouji"
              class-prefix="icon"
              slot="left-icon"
              size="20"
              name="icon-shouji"
            />
          </van-field>
          <van-field
            v-model.trim="form.captcha"
            center
            clearable
            maxlength="6"
            left-icon="smile-comment-o"
            placeholder="请输入短信验证码"
            :rules="[
              {
                required: true,
                message: '请输入验证码',
                trigger: 'onBlur',
              },
            ]"
          >
            <van-icon
              class="iconfont icon-yanzhengma"
              class-prefix="icon"
              slot="left-icon"
              size="20"
            />
            <template #button>
              <van-button
                size="small"
                id="btn"
                plain
                hairline
                round
                @click="CodeBut"
                color="#FDC53D"
                type="primary"
                :disabled="codeBtn"
                >{{ btnMessage }}{{ countDown }}</van-button
              >
            </template>
          </van-field>
          <van-field
            v-model.trim="form.username"
            left-icon="contact"
            maxlength="20"
            @input="form.username = form.username.replace(/[^\w\/]/gi, '')"
            placeholder="请输入登录账号"
            :rules="[
              {
                required: true,
                message: '请输入登录账号',
                trigger: 'onBlur',
              },
              {
                pattern: /^[a-zA-Z0-9]{6,15}$/,
                message: '账号错误，请重新设置6-15位登录账号',
                trigger: 'onChange',
              },
              {
                validator: asyncValidator,
                message: '账号已存在，请重新输入',
                trigger: 'onBlur',
              },
            ]"
          >
            <van-icon
              class="iconfont icon-zhanghao"
              class-prefix="icon"
              slot="left-icon"
              size="20"
            />
          </van-field>
          <van-field
            type="password"
            left-icon="cluster-o"
            v-show="downIcon"
            placeholder="请输入6~15位数字+字母组合密码"
            @click-right-icon="eyeClick"
            right-icon="closed-eye"
            v-model="form.password"
            :rules="[
              {
                required: true,
                message: '请输入登录密码',
                trigger: 'onBlur',
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                message: '密码必须为6-15位字母+数字的随机组合',
                trigger: 'onChange',
              },
            ]"
          >
            <van-icon
              class="iconfont icon-mima"
              class-prefix="icon"
              slot="left-icon"
              size="20"
            />
          </van-field>
          <van-field
            type="text"
            left-icon="icon-zhanghao"
            v-show="!downIcon"
            placeholder="请输入6~15位数字+字母组合密码"
            @click-right-icon="eyeClick"
            right-icon="eye-o"
            v-model="form.password"
            :rules="[
              {
                required: true,
                message: '请输入登录密码',
                trigger: 'onBlur',
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                message: '密码必须为6-15位字母+数字的随机组合',
                trigger: 'onChange',
              },
            ]"
          >
            <van-icon
              class="iconfont icon-mima"
              class-prefix="icon"
              slot="left-icon"
              size="20"
            />
          </van-field>
          <van-field
            v-model.trim="form.inviteCode"
            clearable
            placeholder="请输入服务商推荐码"
            maxlength="6"
            :readonly="readonly"
          >
            <img
              slot="left-icon"
              height="21"
              src="../../assets/img/register_inviteCode.png"
              alt=""
            />
          </van-field>
        </van-cell-group>
        <div class="error-text">{{ errorText }}</div>
        <van-button
          class="login_btn"
          size="small"
          round
          block
          type="info"
          @click="onSubmit"
          :disabled="
            !form.mobile ||
            !form.captcha ||
            !form.username ||
            !form.password ||
            !form.inviteCode
          "
          >确认并登录</van-button
        >
      </van-form>
      <div class="register-agreement">
        <van-checkbox
          v-model="checked"
          @click="checked_but"
          icon-size="18px"
          checked-color="#FEB518"
        ></van-checkbox
        >&nbsp;&nbsp;已阅读并同意
        <span style="color: #ffb72f" @click="jump">《用户注册协议》</span>
      </div>
    </div>
    <van-action-sheet v-model="protocolShow" title="门店注册及服务协议">
      <div class="content">
        <p>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;银行卡四要素是指银行预留的银行卡号码、实名、身份证号码、手机四项数据。银行卡四要素验证是验证银行卡用户数据的真实性，从而建立健全可靠的互联网信用基础。
          银行卡是指商业银行(包括邮政金融机构)向社会认可的，具有消费信贷、转账结算、现金存取等全部或部分功能的信用支付工具。银行卡减少了现金和支票的流通，使银行业务突破了时间和空间的限制，发生了根本性的变化。银行卡自动结算系统的应用，实现了“无支票，无现金社会”的梦想。
          银行卡四要素是指银行预留的银行卡号码、实名、身份证号码、手机四项数据。银行卡四要素验证是验证银行卡用户数据的真实性，从而建立健全可靠的互联网信用基础。
        </p>
        <p>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;银行卡是指商业银行(包括邮政金融机构)向社会认可的，具有消费信贷、转账结算、现金存取等全部或部分功能的信用支付工具。银行卡减少了现金和支票的流通，使银行业务突破了时间和空间的限制，发生了根本性的变化。银行卡自动结算系统的应用，实现了“无支票，无现金社会”的梦想。
        </p>
        <p></p>
      </div>
      <div>
        <van-button
          plain
          style="width: 50%"
          @click="
            protocolShow = false;
            checked = false;
          "
          >不同意</van-button
        >
        <van-button
          color="#FFB72F"
          style="width: 50%"
          @click="
            protocolShow = false;
            checked = true;
          "
          >同意</van-button
        >
      </div>
    </van-action-sheet>
    <van-popup
      v-model="showAgreement"
      position="right"
      :style="{ height: '100%', width: '100%' }"
    >
      <Header-Comp
        title="门店注册及服务协议"
        :leftIconCallback="
          () => {
            showAgreement = false;
          }
        "
      />
      <div class="contents">
        <span v-html="content"></span>
      </div>
    </van-popup>
  </div>
</template>
<script>
import {
  touristAdd,
  sendVerificationCode,
  token,
  getAgentNameByInviteCode,
} from "@/api/register";
import { isBlacklist } from "@/api/merchant";
import { getSystemLimit } from "@/api/system";
import { getUserAgreementInfo } from "@/api/protocol";

export default {
  data() {
    return {
      checked: false,
      form: {
        mobile: "",
        captcha: "",
        username: "",
        password: "",
        // agentUserName: "",
        inviteCode: "",
      },
      agentName: "",
      downIcon: true,
      protocolShow: false,
      errorText: "",
      readonly: false,
      phoneRules: [
        {
          required: true,
          message: "请输入手机号",
          trigger: "onBlur",
        },
        {
          pattern: /^0?(13|14|15|16|17|18|19)[0-9]{9}$/,
          message: "手机号错误请重新输入11位手机号码",
          trigger: "onBlur",
        },
        {
          validator: this.validatePhone,
          message: "暂不支持该手机号段，请更换其他号码重试",
          trigger: "onBlur",
        },
        {
          validator: this.checkBackList,
          message: "手机号填写失败，代码1000",
          trigger: "onBlur",
        },
      ],
      showAgreement: false,
      content: "",
      countDown: "",
      btnMessage: "获取验证码",
      codeBtn: true,
    };
  },
  components: {
    HeaderComp: () => import("@/components/HeaderComp"),
  },
  watch: {
    "form.inviteCode": {
      handler() {
        if (this.form.inviteCode && this.form.inviteCode.length == 6) {
          this.agentName = "";
          this.form.agentUserName = "";
          getAgentNameByInviteCode(
            this.form.inviteCode,
            this.$route.query.tenantId || "000001"
          ).then((res) => {
            if (res.code == 200) {
              const { agentUserName, agentBusinessId, agentNo, agentName } =
                res.data;
              this.form.agentUserName = agentUserName;
              this.form.agentBusinessId = agentBusinessId;
              this.form.agentNo = agentNo;
              this.form.agentName = agentName;
              this.agentName = res.data.agentName;
            }
          });
        }
      },
    },
  },
  created() {
    const {
      deptId = "1123598813738675201",
      inviteCode = "",
      specialFlag = 0,
    } = this.$route.query;
    this.form.deptId = deptId;
    this.form.inviteCode = inviteCode;
    this.form.specialFlag = specialFlag;
    this.readonly = !!inviteCode;
  },
  methods: {
    goBack() {
      document.title = "返回APP";
      // this.$router.go(-1);
    },
    async onSubmit() {
      if (!this.form.mobile) {
        this.errorText = "请输入手机号";
        return;
      } else {
        this.errorText = "";
      }
      var res = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!res.test(this.form.mobile)) {
        this.errorText = "请输入正确手机号";
        return;
      } else {
        this.errorText = "";
      }
      if (!this.form.captcha) {
        this.errorText = "请输入短信验证码";
        return;
      } else {
        this.errorText = "";
      }
      if (!this.form.username) {
        this.errorText = "请输入登录账号";
        return;
      } else {
        this.errorText = "";
      }
      if (!this.form.password) {
        this.errorText = "请输入6~15位数字+字母组合密码";
        return;
      } else {
        this.errorText = "";
      }
      if (this.form.inviteCode && this.form.inviteCode.length != 6) {
        this.errorText = "请输入6位服务商推荐码";
        return;
      } else {
        this.errorText = "";
      }
      if (this.form.inviteCode && !this.form.agentUserName) {
        this.errorText = "请输入正确的服务商推荐码";
        return;
      } else {
        this.errorText = "";
      }
      var name = /^[A-Za-z0-9]{1,20}$/;
      if (!name.test(this.form.username)) {
        return (this.errorText = "请输入数字或字母的账号");
      } else {
        this.errorText = "";
      }
      var pad = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
      if (!pad.test(this.form.password)) {
        this.errorText = "密码必须为6-15位字母+数字的随机组合";
        return;
      } else {
        this.errorText = "";
      }
      // if (!this.form.agentUserName) {
      //   this.errorText = "请输入代理商账号";
      //   return;
      // } else {
      //   this.errorText = "";
      // }
      //   var res = /^1(3|4|5|6|7|8|9)\d{9}$/
      //   if (!res.test(this.form.agentMobile)) {
      //     this.errorText = '请输入正确代理商手机号'
      //     return
      //   } else {
      //     this.errorText = ''
      //   }
      if (this.checked === false) {
        this.errorText = "请勾上已阅读并同意";
        return;
      }
      this.form.tenantId = this.$route.query.tenantId || "000001";
      touristAdd(this.form)
        .then((res) => {
          if (res.code === 200) {
            this.checked = false;
            this.errorText = "";
            this.$toast.success("注册成功");
            token({
              tenantId: this.$route.query.tenantId || "000001",
              username: this.form.username,
              password: this.form.password,
              grant_type: "password",
              scope: "all",
              type: "account",
            }).then((ken) => {
              const url = process.env.VUE_APP_REGISTER_URL;
              const step = location.href.includes("submitInfo")
                ? "/#/submitInfo/step1"
                : "/#/step1";
              const userId = "?userID=" + res.data.id;
              const token = "&token=" + ken.access_token;
              const Autonomy = "&Autonomy=Autonomy";
              const endToDownload = "&endToDownload=1";

              window.location.href =
                url + step + userId + token + Autonomy + endToDownload;
            });
          }
        })

        .catch((err) => {});
    },
    eyeClick() {
      this.downIcon = !this.downIcon;
    },
    checked_but() {
      this.checked != this.checked;
    },
    CodeBut() {
      if (!/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(this.form.mobile)) {
        this.$toast("请输入正确的手机号码");
        return false;
      }
      this.errorText = "";
      this.codeBtn = true;
      this.btnMessage = "获取中";
      sendVerificationCode(
        this.form.mobile,
        this.$route.query.tenantId || "000001"
      )
        .then((res) => {
          if (res.code == 200) {
            this.$toast.success("发送成功!");
            this.countDown = "S";
            this.btnMessage = "60";
            clearInterval(this.tiemerId);
            this.tiemerId = setInterval(() => {
              this.btnMessage--;
              if (this.btnMessage == 0) {
                clearInterval(this.tiemerId);
                this.codeBtn = false;
                this.btnMessage = "获取验证码";
                this.countDown = "";
              }
            }, 1000);
          } else {
            this.$toast({
              type: "fail",
              duration: 1500,
              message: "发送失败",
            });
            this.codeBtn = false;
          }
        })
        .catch((err) => {
          this.$toast({
            type: "fail",
            duration: 1500,
            message: "发送失败",
          });
          this.codeBtn = false;
        });
    },
    validatePhone(val) {
      if (/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(val)) {
        return new Promise((resolve) => {
          getSystemLimit(this.form.deptId).then((res) => {
            let tel = val.substring(0, 3);
            let mobileBlackList = res.data.mobileBlackList;
            if (mobileBlackList.includes(tel)) {
              this.codeBtn = true;
            } else {
              if (this.btnMessage == "获取验证码") {
                this.codeBtn = false;
              }
            }
            resolve(!mobileBlackList.includes(tel));
          });
        });
      }
    },
    // 检查黑名单
    checkBackList(val) {
      return new Promise((resolve) => {
        isBlacklist(val).then(({ data }) => {
          this.phoneRules[3].message = data.consumerHotline
            ? `手机号填写失败，代码1000，请联系客服${data.consumerHotline}`
            : `手机号填写失败，代码1000`;
          resolve(!data.isBlacklist);
        });
      });
    },
    asyncValidator(val) {
      if (/^[a-zA-Z0-9]{6,15}$/.test(val)) {
        return new Promise((resolve) => {
          if (val.length === 11) {
            checkUserName(val, this.form.deptId)
              .then((res) => {
                resolve(res.success);
              })
              .catch((err) => {
                resolve(err.success);
              });
          }
        });
      }
    },
    jump() {
      getUserAgreementInfo({
        deptId: this.$route.query.deptId || "1123598813738675201",
        userAgreementName: "注册协议",
      }).then((res) => {
        this.content = this.$decode(res.data.content);
        this.showAgreement = true;
      });
    },
    getAccountNo(value) {
      const rule = /^0?(13|14|15|16|17|18|19)[0-9]{9}$/;
      this.codeBtn = !rule.test(value);
    },
  },
};
</script>

<style lang="less" scoped>
.register {
  background: #ffffff;
  .register-center {
    text-align: center;
    margin-top: 33px;
    // padding-top: 67px;
    margin-left: 39px;
    margin-right: 39px;
    .van-cell {
      text-align: left;
      color: #393e59;
      padding: 20px 50px;
      .van-field__control {
        color: #454545;
      }
    }
  }
  .register-agreement {
    font-size: 26px;
    color: #9fa6bb;
    text-align: left;
    font-family: PingFangSC-Regular, PingFangSC;
    margin: 24px auto;
    display: flex;
    align-items: center;
    width: 90%;
  }
  .login_btn {
    height: 80px;
    background: #ffb72f;
    border: #ffb72f;
    border-radius: 40px;
    margin: auto;
    margin-top: 40%;
    font-size: 30px;
    width: 90%;
  }
  .error-text {
    height: 26px;
    font-size: 26px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #e42424;
    text-align: left;
    padding: 20px 30px;
  }
}
/deep/ .van-field__left-icon {
  padding-right: 15px;
  color: #000;
}
.content p {
  font-family: PingFang SC;
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  margin: 30px;
}
/deep/ .van-cell-group::after {
  border: none;
}
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  border-bottom: 1px solid #d7d7d7;
  font-size: 36px;
  background: #fff;
  .header-item {
    font-weight: 500;
    color: #131313;
  }
}
.contents {
  padding: 0 38px 50px;
  overflow: scroll;
  height: calc(100vh - 46px - 50px);
}
</style>
